#include <stdio.h>
#include <dlfcn.h>
#include <pthread.h>
#include <signal.h>
#include "common.h"

int looping = 1;
void *g_common_lib = NULL;
pthread_mutex_t mutex;
pthread_t thds[10];

int (*int_int_callfunc)(int, int);

void signal_function(int sig)
{
    printf("reset common lib..\n");
    pthread_mutex_lock(&mutex);
    if (g_common_lib)
        dlclose(g_common_lib);
    int ret = init_common_lib(&g_common_lib); 
    if (ret == -1) 
        printf("init common lib failed!\n");
    pthread_mutex_unlock(&mutex);
}

void thread_testfunction(void *arg)
{
    int a, b;
    a = 10, b = 11;
    int (*int_int_int_callfunc)(int, int);
    int (*int_int_callfunc)(int);
    while (looping) {
        sleep(1);
        if (g_common_lib==NULL) {
            continue;
        } else {
            pthread_mutex_lock(&mutex);
            int_int_callfunc = dlsym(g_common_lib, "AddCount");
            printf("After add, the count is:%d\n", (*int_int_callfunc)(1));
#if 0
            int_int_int_callfunc = dlsym(g_common_lib, "Max");
            printf("The max is:%d\n", (*int_int_int_callfunc)(a,b));
#endif
            pthread_mutex_unlock(&mutex);
        }
    }
}

int init_common_lib(void **dlhdr)
{
    char *(*void_void_callfunc)();
    if (!dlhdr)
        return -1;
    *dlhdr = dlopen("/root/test/dongtaiload/lib/libcommon.so", RTLD_LAZY);
    if (*dlhdr == NULL) {
        printf("dlopen failed!\n");
        return -1;
    }
    void_void_callfunc = dlsym(g_common_lib, "Version");
    printf("The Version of common lib is:%s\n", (void_void_callfunc)());
    return 0;
}

int main(int argc, const char *argv[])
{
    int a = 10, b = 8;
    int ret = init_common_lib(&g_common_lib);
    if (ret == -1)
        return -1;
    signal(SIGINT, signal_function);
    ret = pthread_mutex_init(&mutex, NULL);
    if (ret == -1) {
        printf("init mutex failed!\n");
        return -1;
    }
    //printf("The max number:%d\n", Max(a, b));
    pthread_mutex_lock(&mutex);
    int_int_callfunc = dlsym(g_common_lib, "Max");
    printf("The max number:%d\n", (*int_int_callfunc)(a, b));
    pthread_mutex_unlock(&mutex);

    pthread_create(&thds[0], NULL, thread_testfunction, NULL);

    pthread_join(thds[0], NULL);
    return 0;
}
